import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
class Http {
  // 基础路径
  public baseURL: string = 'https://www.aniu.net.cn:8081/recruit';
  // 超时时间
  private timeout: number = 5000;
  constructor() {}
  mergeOptions(options: AxiosRequestConfig) {
    return {
      baseURL: this.baseURL,
      timeout: this.timeout,
      ...options,
    };
  }
  createInterceptor(instance: AxiosInstance) {
    instance.interceptors.request.use(
      (options) => {
        return options;
      },
      (err) => {
        return Promise.reject(err);
      },
    );
  }
  request(options: AxiosRequestConfig) {
    // 创建单独的axios实例，好处是单独为每个请求创建拦截器
    const instance = axios.create();
    // 设置拦截器
    this.createInterceptor(instance);
    // 合并请求对象
    options = this.mergeOptions(options);
    return instance(options);
  }
  get(url: string, options = {}) {
    return this.request({
      url,
      method: 'get',
      ...options,
    });
  }
  post(url: string, options = {}) {
    return this.request({
      url,
      method: 'post',
      ...options,
    });
  }
  put(url: string, options = {}) {
    return this.request({
      url,
      method: 'put',
      ...options,
    });
  }
}
const http = new Http();
export const baseURL = http.baseURL;
export default http;
